from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated

# Create your views here.

from rest_framework.views import APIView

from userinfo.authentications import generate_jwt, JWTAuthentication
from userinfo.models import User
from userinfo.serialziers import RegisterSerializer, UserSerializer, LoginSerializer
from utils.common.base_response import APIResponse


# 用户注册
class RegisterView(APIView):
    def post(self, request):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.validated_data.pop('re_password')
            user = User.objects.create_user(**serializer.validated_data)
            user.save()
            return APIResponse(msg='注册成功', data=UserSerializer(user).data)
        else:
            return APIResponse(msg="数据传入有误重新输入")


# 登录接口
class LoginView(APIView):
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            token = generate_jwt(user)
            role = user.role
            return APIResponse(msg="登录成功", data={"token": token,
                                                     "user_info": UserSerializer(user).data})
        else:
            return APIResponse(msg="用户名或密码不正确")


# 登陆后首页
class IndexView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    def get(self, request):
        role = request.user.role
        if role == 1:
            return APIResponse(msg='老板页面', code=1)
        elif role == 0:
            return APIResponse(msg='求职页面', code=0)
        else:
            return APIResponse(msg="hr页面", code=2)
